import { loginAPI, reqInfoAPI } from '@/api/user'
import { setToken, getToken, delToken } from '@/utils/storage'
import { Toast } from 'vant'
import router from '@/router'

export default ({
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  mutations: {
    setToken(state, obj) {
      state.token = obj.jwt
    },
    setInfo(state, obj) {
      state.userInfo = obj
    }
  },
  actions: {
    // 登录
    async login(ctx, obj) {
      const res = await loginAPI(obj)
      // console.log(res.data)
      if (res.code === 200) {
        setToken(res.data.jwt)
        Toast.success('登录成功')
        ctx.commit('setToken', res.data)
        router.push('/')
      }     
    },
    // 存用户信息
    async getInfo(ctx) {
      const res = await reqInfoAPI({needToken:true})
      console.log( '需要携带id的数据', res)
      ctx.commit('setInfo', res.data)
    },
    // 退出
    logout({ commit }) {
      delToken()
      commit('setToken', '')
      commit('setInfo', {})
    }
  }
})